"""
@author: xxw
@file: upload_music.py
@time: 2023/8/19 16:14
"""
import pickle

from qiniu import Auth, put_file, etag

# 自己的access_key和secret_key
access_key = 'key'
secret_key = 'key'


# 判断文件是否存在
try:
    with open('song_name.txt', 'rb')as f:
        song_list = pickle.load(f)
except FileNotFoundError:
    raise Exception("the file not found")

for name in song_list:
    # 进行校验
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'mango123'
    # 上传后保存的文件名
    key = name
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    localfile = f'./{name}'
    ret, info = put_file(token, key, localfile, version='v2')
    assert ret['key'] == key
    assert ret['hash'] == etag(localfile)
    if info.status_code != 200:
        raise Exception("upload failed")

with open('song_name.txt', 'w') as f:
    f.truncate(0)